package com.sky.webSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{sid}")
@Slf4j
public class WebSocketServer {

    private static final Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        sessionMap.put(sid, session);
        log.info("客户端:{} 已连接", sid);
    }

    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        if (sid != null) {
            sessionMap.remove(sid);
            log.info("客户端:{} 已断开", sid);
        }
    }

    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        log.info("来自客户端:{} 的消息:{}", sid, message);
    }

    public void sendMessageToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.error("向客户端发送消息失败", e);
                // 可选：清理失效连接
                // sessionMap.values().removeIf(s -> !s.isOpen());
            }
        }
    }
}